package system

import (
	"context"
	"github.com/gogf/gf/v2/net/ghttp"
	"server/internal/model/entity"
	"server/internal/service"
)

const (
	SessionLoginAdminData = "loginAdminData"
)

type sSystemSession struct {
}

func init() {
	service.RegisterSystemSession(&sSystemSession{})
}

func (s *sSystemSession) SetUser(ctx context.Context, admin *entity.SystemUser) (err error) {
	return ghttp.RequestFromCtx(ctx).Session.Set(SessionLoginAdminData, admin)
}

func (s *sSystemSession) GetUser(ctx context.Context) (admin *entity.SystemUser, err error) {
	admin = new(entity.SystemUser)
	result, err := ghttp.RequestFromCtx(ctx).Session.Get(SessionLoginAdminData)
	if err != nil {
		return admin, err
	}
	err = result.Scan(admin)
	return admin, err
}

func (s *sSystemSession) RemoveAll(ctx context.Context) (err error) {
	return ghttp.RequestFromCtx(ctx).Session.RemoveAll()
}

func (s *sSystemSession) GetSessionID(ctx context.Context) (id string, err error) {
	return ghttp.RequestFromCtx(ctx).Session.Id()
}

func (s *sSystemSession) GetLoginAdminID(ctx context.Context) (userId int64) {
	admin, err := s.GetUser(ctx)
	if err != nil {
		return 0
	}
	return int64(admin.Id)
}

func (s *sSystemSession) GetLoginAdminUsername(ctx context.Context) (username string) {
	admin, err := s.GetUser(ctx)
	if err != nil {
		return ""
	}
	return admin.Username
}
